package com.example.vehicle.Function;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SmUtil;

/**
 * @name: AuthenticationTest
 * @description: 测试用身份认证类。
 * @author: Lulu Zhao
 **/
public class AuthenticationTest {

    static String clientID;
    static String initPassword;
    static String hashedPassword;
    static int hashTimes = 30;
    static int currentHashTimes;

    /**
     * @name: main
     * @description: 主函数。
     * @params: [args]
     * @return: void
     * @author: Lulu Zhao
     */
    public static void main(String[] args) {
        currentHashTimes = clientRegister();
        System.out.println("hashedPassword: " + hashedPassword);
        System.out.println("currentHashTimes" + currentHashTimes);
        if (clientAuthentication()) {
            System.out.println("--Client Authentication Program Completed!--");
        }
        System.out.println("hashedPassword: " + hashedPassword);
        System.out.println("currentHashTimes" + currentHashTimes);
    }

    /**
     * @name: clientRegister
     * @description: 模拟车辆注册过程。
     * @params: []
     * @return: int
     * @author: Lulu Zhao
     */
    public static int clientRegister() {
        // 注册分为3步：
        // 1、client向管理者出示个人身份证明（如公民身份信息）和车辆证明；
        // 2、管理者向client发放个人ID和初始口令
        // 3、管理者将哈希后的口令值存入区块链
        //    {"key":"clientID", "value":"PW: hashedPassword; T: currentHashTimes; currentState: init"}
        clientID = IdUtil.simpleUUID();
        initPassword = RandomUtil.randomString(20);
        String calPassword = initPassword;
        for (int i = 0; i < hashTimes; i++) {
            calPassword = SmUtil.sm3(calPassword);
        }
        hashedPassword = calPassword;
        System.out.println("--Client Register Program Completed!--");
        return hashTimes;
    }

    /**
     * @name: clientAuthentication
     * @description: 模拟RSU身份验证过程。
     * @params: []
     * @return: boolean
     * @author: Lulu Zhao
     */
    public static boolean clientAuthentication() {
        // 身份认证过程分为4步：
        // 1、client向RSU发送previousHashedPassword
        // 2、RSU向区块链发起请求获得hashedPassword
        // 3、RSU计算并判断hash(previousHashedPassword)?=hashedPassword
        // 4、若相同则认定client身份并更新区块链
        //    {"key":"clientID", "value":"PW: hashedPassword; T: currentHashTimes; currentState: inuse"}
        //    {"key":"clientID", "value":"PW: hashedPassword; T: currentHashTimes; currentState: abolish"}
        //    若不相同则不认定client身份
        String calPassword = initPassword;
        for (int i = 0; i < currentHashTimes - 1; i++) {
            calPassword = SmUtil.sm3(calPassword);
        }
        if (SmUtil.sm3(calPassword).equals(hashedPassword)) {
            hashedPassword = calPassword;
            currentHashTimes--;
            return true;
        } else {
            return false;
        }
    }
}
